package com.example.administrator.energyida.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.RadioButton;
import android.widget.Toast;

import com.example.administrator.energyida.MainActivity;
import com.example.administrator.energyida.R;
import com.example.administrator.energyida.adapter.ItemExpandableFactoryAdapter;
import com.example.administrator.energyida.beans.CompanyBean;
import com.example.administrator.energyida.beans.FactoryBean;
import com.example.administrator.energyida.beans.WorkshopBean;
import com.example.administrator.energyida.util.OceanUtil;
import com.google.gson.Gson;
import com.jaeger.library.StatusBarUtil;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Pattern;

public class FormFactoryInfoActivity extends Activity implements ItemExpandableFactoryAdapter.Callback {

    private Button btnAddFactory;
    private Button btnSubmit;
    private EditText editTextFactoryName;
    private EditText editTextChargeName;
    private EditText editTextChargePhone;
    private EditText editTextFarmName;
    private EditText editTextFarmChargeName;
    private EditText editTextFarmChargePhone;
    private CheckBox checkBoxFactoryWater;
    private CheckBox checkBoxFactoryElectricity;
    private CheckBox checkBoxFactoryGas;
    private CheckBox checkBoxFactoryHeat;
    private CheckBox checkBoxFarmWater;
    private CheckBox checkBoxFarmElectricity;
    private CheckBox checkBoxFarmGas;
    private CheckBox checkBoxFarmHeat;
    private RadioButton radioButtonCloud;
    private RadioButton radioButtonManual;
    private ExpandableListView listViewFactoryInfo;
    private AlertDialog alert = null;
    private AlertDialog.Builder builder = null;
    private View dialogAddFactory;
    private View dialogAddFarm;
    private View dialogEditFactory;
    private View dialogEditFarm;
    private ItemExpandableFactoryAdapter adapter;
    private ArrayList<HashMap<String, String>> listFactory = new ArrayList<>();
    private ArrayList<ArrayList<HashMap<String, String>>> listFarm = new ArrayList<>();
    private ArrayList<HashMap<String, String>> listgroup_child;

    private List<FactoryBean.ContentBean> listFactoryBeans = new ArrayList<>();
    private List<List<WorkshopBean.ContentBean>> listWorkshopBeans = new ArrayList<>();
    private List<CompanyBean.ContentBean> listCompanyBeans = new ArrayList<>();

    private double companyPointLat;
    private double companyPointLong;
    private String companyName;
    private String companyPhone;

    private String factoryName;
    private String factoryChargeName;
    private String factoryChargePhone;
    private String factoryChargeInfo;
    private String factoryUseWater;
    private String factoryUseElectricity;
    private String factoryUseGas;
    private String factoryUseHeat;

    private String farmName;
    private String farmChargeName;
    private String farmChargePhone;
    private String farmChargeInfo;
    private String farmUseWater;
    private String farmUseElectricity;
    private String farmUseGas;
    private String farmUseHeat;
    private String addMode;

    private String email;
    private String factoryExistResponse;
    private String farmResponse;
    private String farmExistResponse;
    private String getFactoryResponse;
    private String getWorkshopResponse;
    private String getPointResponse;
    private String deleteResponse;
    private Handler handler;

    private Thread threadGetFactory;
    private int groupPosition;

    private QMUITipDialog qmuiTipDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_form_factoryinfo);

        // 设置状态栏的颜色
        StatusBarUtil.setColor(this, Color.parseColor("#10cafd"), 50);

        initView();
        initHandler();
        initExpandableListView();

        //添加工厂
        btnAddFactory.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                final LayoutInflater inflater = FormFactoryInfoActivity.this.getLayoutInflater();
                dialogAddFactory = inflater.inflate(R.layout.view_dialog_addfactory, null);

                editTextFactoryName = dialogAddFactory.findViewById(R.id.addFactory_editText_factoryName);
                editTextChargeName = dialogAddFactory.findViewById(R.id.addFactory_editText_chargeName);
                editTextChargePhone = dialogAddFactory.findViewById(R.id.addFactory_editText_chargePhone);
                checkBoxFactoryWater = dialogAddFactory.findViewById(R.id.addFactory_checkBox_water);
                checkBoxFactoryElectricity = dialogAddFactory.findViewById(R.id.addFactory_checkBox_electricity);
                checkBoxFactoryGas = dialogAddFactory.findViewById(R.id.addFactory_checkBox_gas);
                checkBoxFactoryHeat = dialogAddFactory.findViewById(R.id.addFactory_checkBox_heat);

                builder = new AlertDialog.Builder(FormFactoryInfoActivity.this);
                alert = builder.setView(dialogAddFactory)
                        .setPositiveButton("确定", null)
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        }).create();
                alert.show();
                editTextFactoryName.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                    @Override
                    public void onFocusChange(View v, boolean hasFocus) {
                        if (!hasFocus) {
                            factoryName = editTextFactoryName.getText().toString();
                            JSONObject jsonObject = new JSONObject();
                            try {
                                jsonObject.put("email", email);
                                jsonObject.put("fName", factoryName);
                                jsonObject.put("mode", 1);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                            new OceanUtil("factory.php", jsonObject, new OceanUtil.HttpRequestCallback() {
                                @Override
                                public void callback(String strResponse) {
                                    factoryExistResponse = strResponse;
                                    Message message = new Message();
                                    message.what = 1;
                                    handler.sendMessage(message);
                                }
                            }).postInfo();
                        }
                    }
                });
                alert.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        factoryChargeName = editTextChargeName.getText().toString();
                        factoryChargePhone = editTextChargePhone.getText().toString();
                        factoryChargeInfo = factoryChargeName + "(" + factoryChargePhone + ")";

                        factoryUseWater = "2";
                        factoryUseElectricity = "2";
                        factoryUseGas = "2";
                        factoryUseHeat = "2";

                        if (checkBoxFactoryWater.isChecked()) {
                            factoryUseWater = "1";
                        }
                        if (checkBoxFactoryElectricity.isChecked()) {
                            factoryUseElectricity = "1";
                        }
                        if (checkBoxFactoryGas.isChecked()) {
                            factoryUseGas = "1";
                        }
                        if (checkBoxFactoryHeat.isChecked()) {
                            factoryUseHeat = "1";
                        }

                        if (factoryName.equals("") || factoryChargeName.equals("") || factoryChargePhone.equals("")) {
                            Toast.makeText(FormFactoryInfoActivity.this, "信息必须填写完整", Toast.LENGTH_SHORT).show();
                            return;
                        }

                        if (factoryUseWater.equals("2") && factoryUseElectricity.equals("2") && factoryUseHeat.equals("2") && factoryUseGas.equals("2")) {
                            Toast.makeText(FormFactoryInfoActivity.this, "至少选择一种能源", Toast.LENGTH_SHORT).show();
                            return;
                        }

                        if (!isPhone(factoryChargePhone)) {
                            Toast.makeText(FormFactoryInfoActivity.this, "请填写正确手机号", Toast.LENGTH_SHORT).show();
                            return;
                        }

                        alert.cancel();

                        Intent intent = new Intent();
                        intent.putExtra("companyPointLat", companyPointLat);
                        intent.putExtra("companyPointLong", companyPointLong);
                        intent.putExtra("companyName", companyName);
                        intent.putExtra("companyPhone", companyPhone);
                        intent.putExtra("newName", factoryName);
                        intent.putExtra("fManager", factoryChargeName);
                        intent.putExtra("fPhone", factoryChargePhone);
                        intent.putExtra("useWater", factoryUseWater);
                        intent.putExtra("useElectricity", factoryUseElectricity);
                        intent.putExtra("useGas", factoryUseGas);
                        intent.putExtra("useHeat", factoryUseHeat);

                        intent.setClass(FormFactoryInfoActivity.this, FormMapActivity.class);
                        startActivity(intent);
                    }
                });
            }
        });

        //点击提交按钮
        btnSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String from = getIntent().getStringExtra("from");
                if (from != null) {
                    if (from.equals("personal")) {
                        finish();
                        return;
                    }
                }

                Intent intent = new Intent();
                intent.setClass(FormFactoryInfoActivity.this, MainActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
            }
        });

    }

    @Override
    public void click(View view) {

        final LayoutInflater inflater = FormFactoryInfoActivity.this.getLayoutInflater();

        builder = new AlertDialog.Builder(FormFactoryInfoActivity.this);

        switch (view.getId()) {

            //添加车间
            case R.id.factoryInfo_imageView_addFarm:

                groupPosition = (int) view.getTag(R.id.groupTag);

                dialogAddFarm = inflater.inflate(R.layout.view_dialog_addfarm, null);
                editTextFarmName = dialogAddFarm.findViewById(R.id.addFarm_editText_farmName);
                editTextFarmChargeName = dialogAddFarm.findViewById(R.id.addFarm_editText_chargeName);
                editTextFarmChargePhone = dialogAddFarm.findViewById(R.id.addFarm_editText_chargePhone);
                checkBoxFarmWater = dialogAddFarm.findViewById(R.id.addFarm_checkBox_water);
                checkBoxFarmElectricity = dialogAddFarm.findViewById(R.id.addFarm_checkBox_electricity);
                checkBoxFarmGas = dialogAddFarm.findViewById(R.id.addFarm_checkBox_gas);
                checkBoxFarmHeat = dialogAddFarm.findViewById(R.id.addFarm_checkBox_heat);
                radioButtonCloud = dialogAddFarm.findViewById(R.id.addFarm_radioButton_cloud);
                radioButtonManual = dialogAddFarm.findViewById(R.id.addFarm_radioButton_manual);

                //工厂没有选择的能源车间也不能选择
                factoryUseWater = listFactoryBeans.get(groupPosition).getFWater();
                if (factoryUseWater.equals("2")) {

                    checkBoxFarmWater.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            checkBoxFarmWater.setChecked(false);
                            Toast.makeText(FormFactoryInfoActivity.this, "该能源不可使用", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
                factoryUseElectricity = listFactoryBeans.get(groupPosition).getFElectricity();
                if (factoryUseElectricity.equals("2")) {
                    checkBoxFarmElectricity.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            checkBoxFarmElectricity.setChecked(false);
                            Toast.makeText(FormFactoryInfoActivity.this, "该能源不可使用", Toast.LENGTH_SHORT).show();
                        }
                    });

                }
                factoryUseGas = listFactoryBeans.get(groupPosition).getFGas();
                if (factoryUseGas.equals("2")) {
                    checkBoxFarmGas.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            checkBoxFarmGas.setChecked(false);
                            Toast.makeText(FormFactoryInfoActivity.this, "该能源不可使用", Toast.LENGTH_SHORT).show();
                        }
                    });

                }
                factoryUseHeat = listFactoryBeans.get(groupPosition).getFHeat();
                if (factoryUseHeat.equals("2")) {
                    checkBoxFarmHeat.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            checkBoxFarmHeat.setChecked(false);
                            Toast.makeText(FormFactoryInfoActivity.this, "该能源不可使用", Toast.LENGTH_SHORT).show();
                        }
                    });
                }

                editTextFarmName.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                    @Override
                    public void onFocusChange(View v, boolean hasFocus) {
                        if (!hasFocus) {
                            factoryName = listFactoryBeans.get(groupPosition).getFName();
                            farmName = editTextFarmName.getText().toString();

                            JSONObject jsonObject = new JSONObject();
                            try {
                                jsonObject.put("email", email);
                                jsonObject.put("fName", factoryName);
                                jsonObject.put("wName", farmName);
                                jsonObject.put("mode", 1);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                            new OceanUtil("workshop.php", jsonObject, new OceanUtil.HttpRequestCallback() {
                                @Override
                                public void callback(String strResponse) {
                                    farmExistResponse = strResponse;
                                    Message message = new Message();
                                    message.what = 3;
                                    handler.sendMessage(message);
                                }
                            }).postInfo();
                        }
                    }
                });

                alert = builder.setView(dialogAddFarm)
                        .setPositiveButton("确定", null)
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        }).create();
                alert.show();
                alert.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        factoryName = listFactoryBeans.get(groupPosition).getFName();
                        int fId = Integer.parseInt(listFactoryBeans.get(groupPosition).getFId());

                        farmName = editTextFarmName.getText().toString();
                        farmChargeName = editTextFarmChargeName.getText().toString();
                        farmChargePhone = editTextFarmChargePhone.getText().toString();
                        farmChargeInfo = farmChargeName + "(" + farmChargePhone + ")";

                        farmUseWater = "2";
                        farmUseElectricity = "2";
                        farmUseGas = "2";
                        farmUseHeat = "2";

                        if (checkBoxFarmWater.isChecked()) {
                            farmUseWater = "1";
                        }
                        if (checkBoxFarmElectricity.isChecked()) {
                            farmUseElectricity = "1";
                        }
                        if (checkBoxFarmGas.isChecked()) {
                            farmUseGas = "1";
                        }
                        if (checkBoxFarmHeat.isChecked()) {
                            farmUseHeat = "1";
                        }
                        
                        if (radioButtonCloud.isChecked()) {
                            addMode = "0";
                        }
                        
                        if (radioButtonManual.isChecked()) {
                            addMode = "1";
                        }
                        
                        if (addMode == null) {
                            Toast.makeText(FormFactoryInfoActivity.this, "请选择数据接入方式", Toast.LENGTH_SHORT).show();
                            return;
                        }

                        if (farmName.equals("") || farmChargeName.equals("") || farmChargePhone.equals("")) {
                            Toast.makeText(FormFactoryInfoActivity.this, "信息必须填写完整", Toast.LENGTH_SHORT).show();
                            return;
                        }

                        if (farmUseWater.equals("2") && farmUseElectricity.equals("2") && farmUseGas.equals("2") && farmUseHeat.equals("2")) {
                            Toast.makeText(FormFactoryInfoActivity.this, "至少选择一种能源", Toast.LENGTH_SHORT).show();
                            return;
                        }

                        if (!isPhone(farmChargePhone)) {
                            Toast.makeText(FormFactoryInfoActivity.this, "请填写正确手机号", Toast.LENGTH_SHORT).show();
                            return;
                        }

                        alert.cancel();

                        JSONObject jsonObject = new JSONObject();
                        try {
                            jsonObject.put("email", email);
                            jsonObject.put("fName", factoryName);
                            jsonObject.put("wName", farmName);
                            jsonObject.put("wPhone", Long.parseLong(farmChargePhone));
                            jsonObject.put("wManager", farmChargeName);
                            jsonObject.put("wWater", Integer.parseInt(farmUseWater));
                            jsonObject.put("wElectricity", Integer.parseInt(farmUseElectricity));
                            jsonObject.put("wGas", Integer.parseInt(farmUseGas));
                            jsonObject.put("wHeat", Integer.parseInt(farmUseHeat));
                            jsonObject.put("wMode", Integer.parseInt(addMode));
                            jsonObject.put("mode", 2);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        new OceanUtil("workshop.php", jsonObject, new OceanUtil.HttpRequestCallback() {
                            @Override
                            public void callback(String strResponse) {
                                farmResponse = strResponse;
                                Message message = new Message();
                                message.what = 2;
                                message.arg1 = groupPosition;
                                handler.sendMessage(message);
                            }
                        }).postInfo();


                        listgroup_child = listFarm.get(groupPosition);
                    }
                });
                break;

            //修改工厂
            case R.id.factoryInfo_imageView_editFactory:

                groupPosition = (int) view.getTag(R.id.groupTag);


                dialogEditFactory = inflater.inflate(R.layout.view_dialog_addfactory, null);

                editTextFactoryName = dialogEditFactory.findViewById(R.id.addFactory_editText_factoryName);
                editTextChargeName = dialogEditFactory.findViewById(R.id.addFactory_editText_chargeName);
                editTextChargePhone = dialogEditFactory.findViewById(R.id.addFactory_editText_chargePhone);
                checkBoxFactoryWater = dialogEditFactory.findViewById(R.id.addFactory_checkBox_water);
                checkBoxFactoryElectricity = dialogEditFactory.findViewById(R.id.addFactory_checkBox_electricity);
                checkBoxFactoryGas = dialogEditFactory.findViewById(R.id.addFactory_checkBox_gas);
                checkBoxFactoryHeat = dialogEditFactory.findViewById(R.id.addFactory_checkBox_heat);

                String oldFactoryName = listFactoryBeans.get(groupPosition).getFName();
                double oldLat = listFactoryBeans.get(groupPosition).getFLatitude();
                double oldLong = listFactoryBeans.get(groupPosition).getFLongitude();
                factoryChargeName = listFactoryBeans.get(groupPosition).getFManager();
                factoryChargePhone = listFactoryBeans.get(groupPosition).getFPhone();
                factoryUseWater = listFactoryBeans.get(groupPosition).getFWater();
                factoryUseElectricity = listFactoryBeans.get(groupPosition).getFElectricity();
                factoryUseGas = listFactoryBeans.get(groupPosition).getFGas();
                factoryUseHeat = listFactoryBeans.get(groupPosition).getFHeat();

                if (factoryUseWater.equals("1")) {
                    checkBoxFactoryWater.setChecked(true);
                } else {
                    checkBoxFactoryWater.setChecked(false);
                }
                if (factoryUseElectricity.equals("1")) {
                    checkBoxFactoryElectricity.setChecked(true);
                } else {
                    checkBoxFactoryElectricity.setChecked(false);
                }
                if (factoryUseGas.equals("1")) {
                    checkBoxFactoryGas.setChecked(true);
                } else {
                    checkBoxFactoryGas.setChecked(false);
                }
                if (factoryUseHeat.equals("1")) {
                    checkBoxFactoryHeat.setChecked(true);
                } else {
                    checkBoxFactoryHeat.setChecked(false);
                }

                editTextFactoryName.setText(oldFactoryName);
                editTextChargeName.setText(factoryChargeName);
                editTextChargePhone.setText(factoryChargePhone);

                editTextFactoryName.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                    @Override
                    public void onFocusChange(View v, boolean hasFocus) {
                        if (editTextFactoryName.getText().toString().equals(listFactoryBeans.get(groupPosition).getFName())) {
                            return;
                        }
                        if (!hasFocus) {
                            factoryName = editTextFactoryName.getText().toString();
                            JSONObject jsonObject = new JSONObject();
                            try {
                                jsonObject.put("email", email);
                                jsonObject.put("fName", factoryName);
                                jsonObject.put("mode", 1);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                            new OceanUtil("factory.php", jsonObject, new OceanUtil.HttpRequestCallback() {
                                @Override
                                public void callback(String strResponse) {
                                    factoryExistResponse = strResponse;
                                    Message message = new Message();
                                    message.what = 7;
                                    handler.sendMessage(message);
                                }
                            }).postInfo();
                        }
                    }
                });

                alert = builder.setView(dialogEditFactory)
                        .setPositiveButton("确定", null)
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        }).create();
                alert.show();

                alert.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        factoryName = editTextFactoryName.getText().toString();
                        factoryChargeName = editTextChargeName.getText().toString();
                        factoryChargePhone = editTextChargePhone.getText().toString();
                        factoryChargeInfo = factoryChargeName + "(" + factoryChargePhone + ")";

                        factoryUseWater = "2";
                        factoryUseElectricity = "2";
                        factoryUseGas = "2";
                        factoryUseHeat = "2";

                        if (checkBoxFactoryWater.isChecked()) {
                            factoryUseWater = "1";
                        }
                        if (checkBoxFactoryElectricity.isChecked()) {
                            factoryUseElectricity = "1";
                        }
                        if (checkBoxFactoryGas.isChecked()) {
                            factoryUseGas = "1";
                        }
                        if (checkBoxFactoryHeat.isChecked()) {
                            factoryUseHeat = "1";
                        }

                        if (factoryName.equals("") || factoryChargeName.equals("") || factoryChargePhone.equals("")) {
                            Toast.makeText(FormFactoryInfoActivity.this, "信息必须填写完整", Toast.LENGTH_SHORT).show();
                            return;
                        }

                        if (factoryUseWater.equals("2") && factoryUseElectricity.equals("2") && factoryUseHeat.equals("2") && factoryUseGas.equals("2")) {
                            Toast.makeText(FormFactoryInfoActivity.this, "至少选择一种能源", Toast.LENGTH_SHORT).show();
                            return;
                        }

                        if (!isPhone(factoryChargePhone)) {
                            Toast.makeText(FormFactoryInfoActivity.this, "请填写正确手机号", Toast.LENGTH_SHORT).show();
                            return;
                        }

                        if (!isPhone(factoryChargePhone)) {
                            Toast.makeText(FormFactoryInfoActivity.this, "请填写正确手机号", Toast.LENGTH_SHORT).show();
                            return;
                        }

                        alert.cancel();

                        Intent intent = new Intent();
                        intent.putExtra("reset", true);
                        intent.putExtra("oldName", oldFactoryName);
                        intent.putExtra("oldLat", oldLat);
                        intent.putExtra("oldLong", oldLong);
                        intent.putExtra("companyPointLat", companyPointLat);
                        intent.putExtra("companyPointLong", companyPointLong);
                        intent.putExtra("companyName", companyName);
                        intent.putExtra("companyPhone", companyPhone);
                        intent.putExtra("newName", factoryName);
                        intent.putExtra("fPhone", factoryChargePhone);
                        intent.putExtra("fManager", factoryChargeName);
                        intent.putExtra("useWater", factoryUseWater);
                        intent.putExtra("useElectricity", factoryUseElectricity);
                        intent.putExtra("useGas", factoryUseGas);
                        intent.putExtra("useHeat", factoryUseHeat);

                        intent.setClass(FormFactoryInfoActivity.this, FormMapActivity.class);
                        startActivity(intent);
                    }
                });

                break;

            //修改车间
            case R.id.farmInfo_imageView_editFarm:

                final int cp1 = (int) view.getTag(R.id.childTag);
                groupPosition = (int) view.getTag(R.id.groupTag);

                dialogEditFarm = inflater.inflate(R.layout.view_dialog_addfarm, null);


                editTextFarmName = dialogEditFarm.findViewById(R.id.addFarm_editText_farmName);
                editTextFarmChargeName = dialogEditFarm.findViewById(R.id.addFarm_editText_chargeName);
                editTextFarmChargePhone = dialogEditFarm.findViewById(R.id.addFarm_editText_chargePhone);
                checkBoxFarmWater = dialogEditFarm.findViewById(R.id.addFarm_checkBox_water);
                checkBoxFarmElectricity = dialogEditFarm.findViewById(R.id.addFarm_checkBox_electricity);
                checkBoxFarmGas = dialogEditFarm.findViewById(R.id.addFarm_checkBox_gas);
                checkBoxFarmHeat = dialogEditFarm.findViewById(R.id.addFarm_checkBox_heat);
                radioButtonManual = dialogEditFarm.findViewById(R.id.addFarm_radioButton_manual);
                radioButtonCloud = dialogEditFarm.findViewById(R.id.addFarm_radioButton_cloud);

                String oldWorkshopName = listFarm.get(groupPosition).get(cp1).get("wName");
                farmChargeName = listFarm.get(groupPosition).get(cp1).get("chargeName");
                farmChargePhone = listFarm.get(groupPosition).get(cp1).get("chargePhone");
                farmUseWater = listFarm.get(groupPosition).get(cp1).get("useWater");
                farmUseElectricity = listFarm.get(groupPosition).get(cp1).get("useElectricity");
                farmUseGas = listFarm.get(groupPosition).get(cp1).get("useGas");
                farmUseHeat = listFarm.get(groupPosition).get(cp1).get("useHeat");
                addMode = listFarm.get(groupPosition).get(cp1).get("wMode");

                if (farmUseWater.equals("1")) {
                    checkBoxFarmWater.setChecked(true);
                } else {
                    checkBoxFarmWater.setChecked(false);
                }
                if (farmUseElectricity.equals("1")) {
                    checkBoxFarmElectricity.setChecked(true);
                } else {
                    checkBoxFarmElectricity.setChecked(false);
                }
                if (farmUseGas.equals("1")) {
                    checkBoxFarmGas.setChecked(true);
                } else {
                    checkBoxFarmGas.setChecked(false);
                }
                if (farmUseHeat.equals("1")) {
                    checkBoxFarmHeat.setChecked(true);
                } else {
                    checkBoxFarmHeat.setChecked(false);
                }

                if (addMode.equals("0")) {
                    radioButtonCloud.setChecked(true);
                } else {
                    radioButtonManual.setChecked(true);
                }

                //工厂没有选择的能源车间也不能选择
                factoryUseWater = listFactoryBeans.get(groupPosition).getFWater();
                if (factoryUseWater.equals("2")) {

                    checkBoxFarmWater.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            checkBoxFarmWater.setChecked(false);
                            Toast.makeText(FormFactoryInfoActivity.this, "该能源不可使用", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
                factoryUseElectricity = listFactoryBeans.get(groupPosition).getFElectricity();
                if (factoryUseElectricity.equals("2")) {
                    checkBoxFarmElectricity.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            checkBoxFarmElectricity.setChecked(false);
                            Toast.makeText(FormFactoryInfoActivity.this, "该能源不可使用", Toast.LENGTH_SHORT).show();
                        }
                    });

                }
                factoryUseGas = listFactoryBeans.get(groupPosition).getFGas();
                if (factoryUseGas.equals("2")) {
                    checkBoxFarmGas.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            checkBoxFarmGas.setChecked(false);
                            Toast.makeText(FormFactoryInfoActivity.this, "该能源不可使用", Toast.LENGTH_SHORT).show();
                        }
                    });

                }
                factoryUseHeat = listFactoryBeans.get(groupPosition).getFHeat();
                if (factoryUseHeat.equals("2")) {
                    checkBoxFarmHeat.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            checkBoxFarmHeat.setChecked(false);
                            Toast.makeText(FormFactoryInfoActivity.this, "该能源不可使用", Toast.LENGTH_SHORT).show();
                        }
                    });
                }

                editTextFarmName.setText(oldWorkshopName);
                editTextFarmChargeName.setText(farmChargeName);
                editTextFarmChargePhone.setText(farmChargePhone);

                editTextFarmName.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                    @Override
                    public void onFocusChange(View v, boolean hasFocus) {
                        if (editTextFarmName.getText().toString().equals(listWorkshopBeans.get(groupPosition).get(cp1).getWName())) {
                            return;
                        }
                        if (!hasFocus) {
                            factoryName = listFactoryBeans.get(groupPosition).getFName();
                            farmName = editTextFarmName.getText().toString();

                            JSONObject jsonObject = new JSONObject();
                            try {
                                jsonObject.put("email", email);
                                jsonObject.put("fName", factoryName);
                                jsonObject.put("wName", farmName);
                                jsonObject.put("mode", 1);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                            new OceanUtil("workshop.php", jsonObject, new OceanUtil.HttpRequestCallback() {
                                @Override
                                public void callback(String strResponse) {
                                    farmExistResponse = strResponse;
                                    Message message = new Message();
                                    message.what = 8;
                                    handler.sendMessage(message);
                                }
                            }).postInfo();
                        }
                    }
                });

                alert = builder.setView(dialogEditFarm)
                        .setPositiveButton("确定", null)
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        }).create();
                alert.show();

                alert.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        String fName = listFactoryBeans.get(groupPosition).getFName();
                        int fId = Integer.parseInt(listFactoryBeans.get(groupPosition).getFId());
                        farmName = editTextFarmName.getText().toString();
                        farmChargeName = editTextFarmChargeName.getText().toString();
                        farmChargePhone = editTextFarmChargePhone.getText().toString();
                        farmChargeInfo = farmChargeName + "(" + farmChargePhone + ")";

                        farmUseWater = "2";
                        farmUseElectricity = "2";
                        farmUseGas = "2";
                        farmUseHeat = "2";

                        if (checkBoxFarmWater.isChecked()) {
                            farmUseWater = "1";
                        }
                        if (checkBoxFarmElectricity.isChecked()) {
                            farmUseElectricity = "1";
                        }
                        if (checkBoxFarmGas.isChecked()) {
                            farmUseGas = "1";
                        }
                        if (checkBoxFarmHeat.isChecked()) {
                            farmUseHeat = "1";
                        }

                        if (radioButtonCloud.isChecked()) {
                            addMode = "0";
                        }

                        if (radioButtonManual.isChecked()) {
                            addMode = "1";
                        }

                        if (addMode == null) {
                            Toast.makeText(FormFactoryInfoActivity.this, "请选择数据接入方式", Toast.LENGTH_SHORT).show();
                            return;
                        }

                        if (farmName.equals("") || farmChargeName.equals("") || farmChargePhone.equals("")) {
                            Toast.makeText(FormFactoryInfoActivity.this, "信息必须填写完整", Toast.LENGTH_SHORT).show();
                            return;
                        }

                        if (farmUseWater.equals("2") && farmUseElectricity.equals("2") && farmUseGas.equals("2") && farmUseHeat.equals("2")) {
                            Toast.makeText(FormFactoryInfoActivity.this, "至少选择一种能源", Toast.LENGTH_SHORT).show();
                            return;
                        }

                        if (!isPhone(farmChargePhone)) {
                            Toast.makeText(FormFactoryInfoActivity.this, "请填写正确手机号", Toast.LENGTH_SHORT).show();
                            return;
                        }

                        alert.cancel();

                        JSONObject jsonObject = new JSONObject();
                        try {
                            jsonObject.put("email", email);
                            jsonObject.put("fName", fName);
                            jsonObject.put("oldName", oldWorkshopName);
                            jsonObject.put("newName", farmName);
                            jsonObject.put("wPhone", Long.parseLong(farmChargePhone));
                            jsonObject.put("wManager", farmChargeName);
                            jsonObject.put("wWater", Integer.parseInt(farmUseWater));
                            jsonObject.put("wElectricity", Integer.parseInt(farmUseElectricity));
                            jsonObject.put("wGas", Integer.parseInt(farmUseGas));
                            jsonObject.put("wHeat", Integer.parseInt(farmUseHeat));
                            jsonObject.put("wMode", addMode);
                            jsonObject.put("mode", 2);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        new OceanUtil("resetWorkshop.php", jsonObject, new OceanUtil.HttpRequestCallback() {
                            @Override
                            public void callback(String strResponse) {
                                farmResponse = strResponse;
                                Message message = new Message();
                                message.what = 6;
                                message.arg1 = fId;
                                handler.sendMessage(message);
                            }
                        }).postInfo();

                    }
                });

                break;

            default:
                break;
        }
    }

    void initView() {
        btnAddFactory = findViewById(R.id.formFactoryinfo_btn_addFactory);
        btnSubmit = findViewById(R.id.formFactoryInfo_btn_submit);

        SharedPreferences sharedPreferences = getSharedPreferences("account", MODE_PRIVATE);
        email = sharedPreferences.getString("email", "");

        JSONObject getPoint = new JSONObject();
        try {
            getPoint.put("email", email);
            getPoint.put("mode", 1);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        new OceanUtil("getAccountAllInfo.php", getPoint, new OceanUtil.HttpRequestCallback() {
            @Override
            public void callback(String strResponse) {
                getPointResponse = strResponse;
                Message message = new Message();
                message.what = 0;
                handler.sendMessage(message);
            }
        }).postInfo();
    }

    void initExpandableListView() {
        listViewFactoryInfo = findViewById(R.id.formFactoryInfo_listView_factoryInfo);
        adapter = new ItemExpandableFactoryAdapter(listFactory, listFarm, FormFactoryInfoActivity.this, this);
        listViewFactoryInfo.setAdapter(adapter);

        FormFactoryInfoActivity.this.registerForContextMenu(listViewFactoryInfo);
    }

    @SuppressLint("HandlerLeak")
    private void initHandler() {
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    //获得公司坐标
                    case 0:
                        if (getPointResponse.contains("10007")) {
                            Log.i("坐标", "获得公司信息成功 ");
                            Gson gson = new Gson();
                            CompanyBean companyBean = gson.fromJson(getPointResponse, CompanyBean.class);
                            listCompanyBeans = companyBean.getContent();

                            companyName = listCompanyBeans.get(0).getCompany();
                            companyPointLat = listCompanyBeans.get(0).getLatitude();
                            companyPointLong = listCompanyBeans.get(0).getLongitude();
                        }
                        if (getPointResponse.contains("-20007")) {
                            Toast.makeText(FormFactoryInfoActivity.this, "公司坐标获取失败", Toast.LENGTH_SHORT).show();
                        }
                        break;
                    //判断工厂名称是否重复
                    case 1:
                        if (factoryExistResponse.contains("10008")) {

                        }
                        if (factoryExistResponse.contains("-20008")) {
                            Toast.makeText(FormFactoryInfoActivity.this, "工厂名称不能重复", Toast.LENGTH_SHORT).show();
                            editTextFactoryName = dialogAddFactory.findViewById(R.id.addFactory_editText_factoryName);
                            editTextFactoryName.setText("");
                        }
                        break;
                    //提交车间
                    case 2:
                        if (farmResponse.contains("10012")) {
                            listFactoryBeans.clear();
                            listWorkshopBeans.clear();
                            getFactoryData();
                            listViewFactoryInfo.expandGroup(msg.arg1);
                        }
                        if (farmResponse.contains("-20012")) {
                            Toast.makeText(FormFactoryInfoActivity.this, "添加失败", Toast.LENGTH_SHORT).show();
                        }
                        break;
                    //判断车间名称是否重复
                    case 3:
                        if (farmExistResponse.contains("10008")) {

                        }
                        if (farmExistResponse.contains("-20008")) {
                            Toast.makeText(FormFactoryInfoActivity.this, "车间名不能重复", Toast.LENGTH_SHORT).show();
                            editTextFarmName = dialogAddFarm.findViewById(R.id.addFarm_editText_farmName);
                            editTextFarmName.setText("");
                        }
                        break;
                    //获取所有工厂数据
                    case 4:
                        if (getFactoryResponse.contains("10007")) {

                            Gson gsonFactory = new Gson();
                            FactoryBean factoryBean = gsonFactory.fromJson(getFactoryResponse, FactoryBean.class);
                            listFactoryBeans = factoryBean.getContent();
                            listFactory.clear();


                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    for (int i = 0; i < listFactoryBeans.size(); i++) {
                                        int fId = Integer.parseInt(listFactoryBeans.get(i).getFId());
                                        String fName = listFactoryBeans.get(i).getFName();
                                        String fManager = listFactoryBeans.get(i).getFManager();
                                        String fPhone = listFactoryBeans.get(i).getFPhone();
                                        String fMInfo = fManager + "(" + fPhone + ")";

                                        HashMap<String, String> hashMap = new HashMap<>();
                                        hashMap.put("fName", fName);
                                        hashMap.put("fMInfo", fMInfo);

                                        listFactory.add(hashMap);

                                        ArrayList<HashMap<String, String>> listGroup_child = new ArrayList<>();
                                        listFarm.add(listGroup_child);

                                        getWorkshopData(fId);

                                    }
                                    Message message = new Message();
                                    message.what = 5;
                                    handler.sendMessage(message);
                                }
                            }).start();

                        }
                        if (getFactoryResponse.contains("-20007")) {
                            Toast.makeText(FormFactoryInfoActivity.this, "还没有添加工厂", Toast.LENGTH_SHORT).show();
                            qmuiTipDialog.dismiss();
                        }
                        break;
                    //获取车间数据
                    case 5:
                        for (int i = 0; i < listWorkshopBeans.size(); i++) {
                            ArrayList<HashMap<String, String>> listGroup_child = listFarm.get(i);
                            listGroup_child.clear();
                            for (int j = 0; j < listWorkshopBeans.get(i).size(); j++) {
                                String wName = listWorkshopBeans.get(i).get(j).getWName();
                                String wManager = listWorkshopBeans.get(i).get(j).getWManager();
                                String wPhone = listWorkshopBeans.get(i).get(j).getWPhone();
                                String wMInfo = wManager + "(" + wPhone + ")";
                                String wWater = listWorkshopBeans.get(i).get(j).getWWater();
                                String wElectricity = listWorkshopBeans.get(i).get(j).getWElectricity();
                                String wGas = listWorkshopBeans.get(i).get(j).getWGas();
                                String wHeat = listWorkshopBeans.get(i).get(j).getWHeat();
                                String wMode = listWorkshopBeans.get(i).get(j).getMode();

                                HashMap<String, String> hashMap = new HashMap<>();
                                hashMap.put("wName", wName);
                                hashMap.put("wMInfo", wMInfo);
                                hashMap.put("chargeName", wManager);
                                hashMap.put("chargePhone", wPhone);
                                hashMap.put("useWater", wWater);
                                hashMap.put("useElectricity", wElectricity);
                                hashMap.put("useGas", wGas);
                                hashMap.put("useHeat", wHeat);
                                hashMap.put("wMode", wMode);
                                listGroup_child.add(hashMap);
                                listFarm.add(listGroup_child);
                            }
                        }
                        adapter.notifyDataSetChanged();

                        //关闭加载框
                        qmuiTipDialog.dismiss();
                        break;
                    //修改车间
                    case 6:
                        if (farmResponse.contains("10021")) {
                            listFactoryBeans.clear();
                            listWorkshopBeans.clear();
                            getFactoryData();
                        }
                        if (farmResponse.contains("-20021")) {
                            Toast.makeText(FormFactoryInfoActivity.this, "车间修改失败", Toast.LENGTH_SHORT).show();
                        }
                        break;
                    //修改工厂判断重复
                    case 7:
                        if (factoryExistResponse.contains("10008")) {

                        }
                        if (factoryExistResponse.contains("-20008")) {
                            Toast.makeText(FormFactoryInfoActivity.this, "工厂名称不能重复", Toast.LENGTH_SHORT).show();
                            editTextFactoryName = dialogEditFactory.findViewById(R.id.addFactory_editText_factoryName);
                            editTextFactoryName.setText("");
                        }
                        break;
                    //修改车间判断重复
                    case 8:
                        if (farmExistResponse.contains("10008")) {

                        }
                        if (farmExistResponse.contains("-20008")) {
                            Toast.makeText(FormFactoryInfoActivity.this, "车间名不能重复", Toast.LENGTH_SHORT).show();
                            editTextFarmName = dialogEditFarm.findViewById(R.id.addFarm_editText_farmName);
                            editTextFarmName.setText("");
                        }
                        break;
                    //删除工厂或车间
                    case 9:
                        if (deleteResponse.contains("10002")) {
                            listFactoryBeans.clear();
                            listWorkshopBeans.clear();
                            getFactoryData();
                        }
                        if (deleteResponse.contains("-20002")) {
                            Toast.makeText(FormFactoryInfoActivity.this, "删除失败", Toast.LENGTH_SHORT).show();
                        }
                        break;
                    default:
                        break;
                }

            }
        };
    }

    //获取工厂数据    调用后获取所有工厂数据和所有车间数据并且刷新列表
    private void getFactoryData() {
        JSONObject getFactory = new JSONObject();
        try {
            getFactory.put("email", email);
            getFactory.put("mode", 2);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        qmuiTipDialog = new QMUITipDialog.Builder(this)
                .setIconType(QMUITipDialog.Builder.ICON_TYPE_LOADING)
                .setTipWord("正在加载")
                .create();
        qmuiTipDialog.show();

        new OceanUtil("getAccountAllInfo.php", getFactory, new OceanUtil.HttpRequestCallback() {
            @Override
            public void callback(String strResponse) {
                getFactoryResponse = strResponse;
                Message message = new Message();
                message.what = 4;
                handler.sendMessage(message);
            }
        }).postInfo();
    }

    //获取车间数据    不能单独调用
    private void getWorkshopData(int fId) {

        JSONObject jsonGetWorkshop = new JSONObject();
        try {
            jsonGetWorkshop.put("email", email);
            jsonGetWorkshop.put("mode", 3);
            jsonGetWorkshop.put("factory", fId);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        new OceanUtil("getAccountAllInfo.php", jsonGetWorkshop, new OceanUtil.HttpRequestCallback() {
            @Override
            public void callback(String strResponse) {
                Gson gson = new Gson();
                WorkshopBean workshopBean = gson.fromJson(strResponse, WorkshopBean.class);
                listWorkshopBeans.add(workshopBean.getContent());
            }
        }).AsynPostInfo();
    }

    //判断手机号码
    private boolean isPhone(String phone) {
        if (phone.length() != 11) {
            return false;
        }
        String s1="^((17[0-9])|(14[0-9])|(13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$";
        return Pattern.matches(s1, phone);
    }

    //长按删除
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        if (v.getId() == R.id.formFactoryInfo_listView_factoryInfo) {
            getMenuInflater().inflate(R.menu.contextmenu, menu);
        }
        super.onCreateContextMenu(menu, v, menuInfo);
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        ExpandableListView.ExpandableListContextMenuInfo info = (ExpandableListView.ExpandableListContextMenuInfo) item.getMenuInfo();
        int type = ExpandableListView.getPackedPositionType(info.packedPosition);
        int groupPos = ExpandableListView.getPackedPositionGroup(info.packedPosition);
        int childPos = ExpandableListView.getPackedPositionChild(info.packedPosition);

        if (item.getItemId() == R.id.contextMenu_delete) {
            String fId = listFactoryBeans.get(groupPos).getFId();
            if (type == ExpandableListView.PACKED_POSITION_TYPE_GROUP) {
                JSONObject jsonObject = new JSONObject();
                try {
                    jsonObject.put("email", email);
                    jsonObject.put("mode", 1);
                    jsonObject.put("fId", fId);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                new OceanUtil("deleteAccountAllInfo.php", jsonObject, new OceanUtil.HttpRequestCallback() {
                    @Override
                    public void callback(String strResponse) {
                        deleteResponse = strResponse;
                        Message message = new Message();
                        message.what = 9;
                        handler.sendMessage(message);
                    }
                }).postInfo();
            }
            if (type == ExpandableListView.PACKED_POSITION_TYPE_CHILD) {
                String wId = listWorkshopBeans.get(groupPos).get(childPos).getWId();
                JSONObject jsonObject = new JSONObject();
                try {
                    jsonObject.put("email", email);
                    jsonObject.put("mode", 2);
                    jsonObject.put("fId", fId);
                    jsonObject.put("wId", wId);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                new OceanUtil("deleteAccountAllInfo.php", jsonObject, new OceanUtil.HttpRequestCallback() {
                    @Override
                    public void callback(String strResponse) {
                        deleteResponse = strResponse;
                        Message message = new Message();
                        message.what = 9;
                        handler.sendMessage(message);
                    }
                }).postInfo();
            }
        }
        return super.onContextItemSelected(item);
    }

    @Override
    protected void onResume() {
        listFactoryBeans.clear();
        listWorkshopBeans.clear();
        getFactoryData();
        super.onResume();
    }
}
